package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-04-03
 * Time: 1:00
 */
public class UDPEchoClient {
    private DatagramSocket socket = null;
    private String serverIP;
    private int serverPort;

    //确定服务器
    public UDPEchoClient(String serverIP, int serverPort) throws SocketException {
        this.socket = new DatagramSocket();
        this.serverIP = serverIP;
        this.serverPort = serverPort;
    }


    public void start() throws IOException {
        //客户端输入信息
        Scanner scanner = new Scanner(System.in);
        while(true) {
            System.out.print("-> ");
            String request = scanner.nextLine();
            //next方法以空格或者回车分割！
            //控制台输入数据报的【主信息】

            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length,
                    InetAddress.getByName(serverIP), serverPort);
            //打包信息成数据报
            //根据ip打包成InetAddress对象

            socket.send(requestPacket);
            //发送给服务器

            DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
            //等待服务器返回响应
            //而两个机器之间是通过数据报传输

            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            //获取数据报里面的响应信息！

            System.out.printf("服务器[%s, %d], 收到请求[request]:%s, 发来响应[response]:%s\n", serverIP,
                    serverPort, request, response);
            //打印日志
        }

    }


    public static void main(String[] args) throws IOException {
        UDPEchoClient udpEchoClient = new UDPEchoClient("10.61.10.239", 9090);
        udpEchoClient.start();
    }
}
